﻿using DoNet.Extensions.Common;
using DoNet.Extensions.ServiceExtensions;
using DoNet.ThirdParty.UAParser;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using SqlSugar.Extensions;
using System.Reflection;

namespace DoNet.Extensions.Filters
{
    /// <summary>
    /// 表示一个特性，该特性用于全局捕获程序运行异常信息。
    /// </summary>
    public class GlobalExceptionsFilter : IExceptionFilter
    {
        /// <summary>
        /// 
        /// </summary>
        //private readonly ILogService _service;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="service"></param>
        public GlobalExceptionsFilter() //ILogService service
        {
            //_service = service;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            var exception = context.Exception;

            var httpContext = context.HttpContext;
            var httpRequest = httpContext.Request;
            var type = MethodBase.GetCurrentMethod()?.DeclaringType;
            //CommonResult result = new CommonResult();
            string errMsg = string.Empty;
            string errCode = string.Empty;

            if (exception is MyApiException myApiex)
            {
                context.HttpContext.Response.StatusCode = 200;
                context.ExceptionHandled = true;
                errMsg = myApiex.Msg;
                errCode = myApiex.ErrCode;
            }
            else
            {
                errMsg = "程序异常,服务端出现异常![异常消息]" + exception.Message;
                errCode = "500";
            }
            context.Result = new JsonResult(new { ErrMsg= errMsg, ErrCode = errCode });
            var headers = httpRequest.Headers;
            var clientInfo = headers.ContainsKey("User-Agent") ? UAParserSetup.GetClientInfo(headers["User-Agent"].ObjToString()) : null;
            var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
            var ip = httpContext.GetClientUserIp();

            #region 异常记录
            //Log logEntity = new Log()
            //{
            //    Date = DateTime.Now,
            //    Account = Appsettings.UserClaims?.FindFirstValue(YuebonClaimConst.UserName),
            //    RealName = Appsettings.UserClaims?.FindFirstValue(YuebonClaimConst.RealName),
            //    IPAddress = ip,
            //    RequestUrl = httpRequest.Path,
            //    OS = clientInfo.OS.Family + clientInfo.OS.Major,
            //    Browser = clientInfo.UA.Family + clientInfo.UA.Major,
            //    ModuleName = context.Controller.ToString(),
            //    MethodName = actionDescriptor?.ActionName,
            //    RequestMethod = httpRequest.Method,
            //    ExceptionType = exception.GetType().Name,
            //    Description = $"异常信息：{exception.Message} \r\n【堆栈调用】：\r\n{exception.StackTrace}"
            //};
            //_service.Insert(logEntity);
            #endregion
        }
    }
}
